﻿using ETModel;
using System.Collections.Generic;
using UnityEngine;

namespace ETHotfix {
    public static class GameUnitFactory {
        public static void LoadUnitsByInfos(IEnumerable<UnitInfo> units) {
            foreach (var unitInfo in units) {
                LoadUnitByInfo(unitInfo);
            }
        }

        /// <summary>
        /// 根据配置加载u3d对象
        /// </summary>
        /// <param name="BundleName"></param>
        /// <param name="BundlePrefabName"></param>
        /// <param name="GameObjectRefName"></param>
        /// <returns></returns>
        public static GameObject LoadGameObjectByBundle(string BundleName, string BundlePrefabName, string GameObjectRefName) {

            GameObject gameObj = null;

            ResourcesComponent resourcesComponent = ETModel.Game.Scene.GetComponent<ResourcesComponent>();
            GameObject bundleGameObject
                = (GameObject)resourcesComponent.GetAsset(BundleName, BundlePrefabName);
            GameObject prefab = bundleGameObject.Get<GameObject>(GameObjectRefName);
            gameObj = UnityEngine.Object.Instantiate(prefab);

            return gameObj;
        }

        public static Unit LoadUnitByInfo(UnitInfo unitInfo) {

            UnitsComponent unitComponent = Game.Scene.GetComponent<UnitsComponent>();
            var unit = unitComponent.Get(unitInfo.UnitId);
            if (unit != null) {
                //id已存在,则直接返回
                return unit;
            }
            unit = CreateUnit(unitInfo, "Unit.unity3d", "Unit", "Skeleton");
            unitComponent.Add(unit);
            return unit;
        }

        public static GameUnit CreateUnit(UnitInfo unitInfo, string BundleName, string BundlePrefabName, string GameObjectRefName) {

            GameObject unitGameObj = LoadGameObjectByBundle(BundleName, BundlePrefabName, GameObjectRefName);

            GameUnit unit = ComponentFactory.CreateWithId
                <GameUnit, GameObject, UnitInfo>(unitInfo.UnitId, unitGameObj, unitInfo);
            
            //单位默认都加上这些组件
            unit.AddComponent<AnimatorComponent>();
            unit.AddComponent<MoveComponent>();
            unit.AddComponent<TurnComponent>();
            unit.AddComponent<UnitPathComponent>();

            return unit;
        }
    }
}